package com.sxt.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

public class MyShiroDemo {
    public static void main(String[] args) {
        //1、解析ini文件内容
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2、获得securityManager对象
        SecurityManager securityManager = factory.getInstance();
        //3、将securityManager对象保存到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        //4、获得主体subject用户保存ini文件信息
        Subject subject = SecurityUtils.getSubject();
        //5、用户输入用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken("James", "123");
        //6、把subject中保存的ini信息和用户输入的登录信息比对
        try {
            //用户认证--subject中存放的是用户登录成功的信息
            subject.login(token);
            System.out.println("登录成功！");
            //[1]可以获取登录成功后的用户名
            Object username = subject.getPrincipal();
            System.out.println(username);
            //[2]判断用户是否含有某角色
            boolean flag = subject.hasRole("role1");
            System.out.println(flag);
            //[3]判断用户是否具有指定角色的权限，如果没有参数中的权限会报错，有则正常执行
            subject.checkPermission("update");

            boolean permitted = subject.isPermitted("select");
            System.out.println(permitted);//输出true/false

        } catch (IncorrectCredentialsException e) {
            System.out.println("凭证不正确");
        }catch (UnknownAccountException e){
            System.out.println("账户不正确");
        }catch (Exception e){
            System.out.println( "认证失败！");
        }


    }
}
